<template>
	<view class="uni-container">
		<uni-forms ref="form" :model="formData" validate-trigger="submit" err-show-type="toast">
			<uni-forms-item name="type_id" label="服务类型">
				<uni-data-picker v-model="formData.type_id" placeholder="点击选择" popup-title="点击选择"
					collection="yycw_car_service_type" field="service_name as text, _id as value"></uni-data-picker>
			</uni-forms-item>
			<uni-forms-item name="customer_phone" label="联系方式">
				<uni-easyinput type="number" placeholder="填写电话" v-model="formData.customer_phone" trim="all"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="customer_needs" label="简述需求">
				<uni-easyinput placeholder="填写您的养车需求，期望的取车时间" v-model="formData.customer_needs" type="textarea"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="customer_location" label="车辆位置">
				<uni-row>
					<uni-col :span="16">
						<uni-easyinput :disabled="true" v-model="formData.customer_location.name"></uni-easyinput>
					</uni-col>
					<uni-col :span="8">
						<button size="mini" type="primary" @tap="chooseCustomerAddress">选择位置</button>
					</uni-col>
				</uni-row>
			</uni-forms-item>
			<uni-forms-item name="butler_id" label="车管家">
				<uni-data-picker v-model="formData.butler_id" placeholder="点击选择您的专属车管家" popup-title="选择您的专属车管家"
					collection="uni-id-users" field="nickname as text, _id as value"
					:where="`role == 'butler'`"></uni-data-picker>
			</uni-forms-item>
			<uni-forms-item name="store_id" label="联盟门店">
				<uni-data-picker v-model="formData.store_id" placeholder="点击选择宇壹联盟门店" popup-title="点击选择宇壹联盟门店"
					collection="yycw_store" field="store_name as text, _id as value"></uni-data-picker>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" @click="submit">派单</button>
			</view>
		</uni-forms>
	</view>

	<uni-popup ref="customPopup" type="bottom">
		<view class="custom-picker-popup">
			<scroll-view scroll-y class="list-container">
				<uni-card v-for="(item, index) in formOptions.store_list" :key="item.value" :title="item.text"
					:sub-title="item.sub_title" :thumbnail="item.image" @click="handleCustomSelect(item)">
					<template v-slot:extra>
						<image :src="item.image" mode="aspectFill" class="card-image" />
					</template>
				</uni-card>
			</scroll-view>
		</view>
	</uni-popup>
</template>

<script>
	import {
		validator
	} from '../../js_sdk/validator/yycw_car_service_order.js';
	const serviceOrder = uniCloud.importObject('yycw-carservice-co')
	const db = uniCloud.database();
	const dbCollectionName = 'yycw_car_service_order';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.indexOf(key) > -1) {
				result[key] = validator[key]
			}
		}
		return result
	}

	export default {
		data() {
			let formData = {
				"type_id": "",
				"plate_number": "",
				"archives_id": "",
				"customer_needs": "1：\n2：\n3：\n4：\n...",
				"customer_phone": "",
				"store_id": "",
				"butler_id": "",
				"offer_price": 0.0,
				"customer_location": {
					name: "请选择位置"
				}
			}
			return {
				formData,
				tempIds: {
					user: ['mjGiya6sEGbNqdJ7olO7IqBXSCXj-XVdnOlE_3XJwy8',
						'Amqj8HYXmD0KAuZ7-eWqhMZFQ_HqpUBPrA_hHXQFfs4'
					]
				},
				formOptions: {
					store_list: [{
						value: "1",
						text: "宇壹车务",
						sub_title: "拖车救援",
						image: "https://mp-6fb2680d-8625-4497-8e9b-9e026f99b673.cdn.bspapp.com/cloudstorage/006609fa-1d82-4a08-9f07-2168e794abf4.jpg",
					}],
				},
				whereCondition: {
					role: db.command.in(['butler']),
					status: 0
				},
				rules: {
					...getValidator(Object.keys(formData))
				}
			}
		},
		onLoad(option) {
			// 接收并设置参数
			if (option.type_id) {
				this.formData.type_id = option.type_id;
			}
			if (option.plate_number) {
				this.formData.plate_number = option.plate_number;
			}
			if (option.archives_id) {
				this.formData.archives_id = option.archives_id;
			}
			if (option.butler_id) {
				this.formData.butler_id = option.butler_id;
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.requestSubscribeMessage({
					tmplIds: this.tempIds.user,
					success: (res) => {},
					fail: (res) => {
						uni.showToast({
							title: '订阅消息模板错误',
							icon: 'error',
							duration: 1000
						});
						if (20001 === res.errCode) {
							console.debug('sub fail no temp return')
						}
					},
				})
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},
			/**
			 * 提交表单
			 */
			async submitForm(value) {
				return db.collection(dbCollectionName).add(value).then((res) => {
					const timer = setTimeout(() => uni.reLaunch({
						url: '/pages/index/index'
					}), 5000)
					uni.showModal({
						icon: 'success',
						content: '您已派单成功，正在等待初审...\n\r可以在我的-派单历史查询工单状态',
						confirmColor: '#2A7A72',
						showCancel: false,
						success: function() {
							uni.reLaunch({
								url: '/pages/index/index'
							})
							clearTimeout(timer)
							return
						}
					})
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			},
			chooseCustomerAddress() {
				uni.chooseLocation({
					latitude: this.formData.customer_location.latitude, // 示例纬度
					longitude: this.formData.customer_location.longitude, // 示例经度
					keyword: (this.formData.customer_location.name !== '请选择位置' && this.formData.customer_location
						.name) || '',
					success: (res) => {
						// 类型安全的赋值
						this.formData.customer_location = {
							name: res.name || '未知位置',
							address: res.address || '',
							latitude: Number(res.latitude) || 0,
							longitude: Number(res.longitude) || 0
						}
						// console.debug('chooseLocation res:' + JSON.stringify(res))

					},
					fail: (err) => {
						console.error('地址选择失败:', err)
						uni.showToast({
							title: '地址选择取消或失败',
							icon: 'none'
						})
					}
				})
			},
		}
	}
</script>

<style>
	.uni-container {
		padding: 15px;
		background: #F5F0E6;
		min-height: 100vh;
	}

	.uni-input-border,
	.uni-textarea-border {
		width: 100%;
		font-size: 14px;
		color: #424B54;
		border: 1px #e5e5e5 solid;
		border-radius: 5px;
		box-sizing: border-box;
	}

	.uni-input-border {
		padding: 0 10px;
		height: 35px;
	}

	.uni-textarea-border {
		padding: 10px;
		height: 80px;
	}

	.uni-button-group {
		margin-top: 50px;
		display: flex;
		justify-content: center;
	}

	.uni-button {
		width: 184px;
		background: #2A7A72;
	}

	.uni-button:active {
		background: #1F5D57;
	}
</style>